package com.easyattendance.services;


import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Section;
import com.easyattendance.model.Teacher;
import com.easyattendance.model.User;
import com.easyattendance.util.HibernateUtil;

public class AddSectionService {
	
   /* public boolean authenticatePassword(String deptName, String oldPassword, String newPassword) {
    	Department user = getDepartmentByDeptName(deptName);          
        if(user!=null && user.getDept_name().equals(deptName) && user.getPassword().equals(oldPassword)){
        	updatePassword(deptName,newPassword);
            return true;
        }else{ 
            return false;
        }
    }*/

	/* Method to CREATE a department in the database */
	   public synchronized boolean addSection(Section section){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();
	         
	         //result = ifAlreadyExists(department.getDept_name());
	         
	         /*we can also set student fields here by passing values as arguments
	          * 
	          * Employee employee = new Employee();
	         employee.setFirstName(fname);
	         employee.setLastName(lname);
	         employee.setSalary(salary);*/
	         //if (result == false) {
	        	 session.save(section);
	           	 tx.commit();
	           	 result=true;
	         //}
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to update a department in the database */
	   public synchronized boolean updateSection(Section section){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();
	        	 session.update(section);
	           	 tx.commit();
	           	 result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to DELETE a section from the records */
	   public synchronized boolean deleteSection(String emailId){
		   Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean flag = false;
	      try{
	         tx = session.beginTransaction();
	         List list  = session.createQuery("FROM User").list();
	         for(Iterator itr = list.iterator(); itr.hasNext(); ) {
	        	 User user = (User) itr.next();
	        	 
	        	 if(user.getEmail_id().equals(emailId)) {
	        		 session.delete(user);
	        		 break;
	        	 }
	         }
	        
	         /*Section section = getSectionBySectionEmail(emailId);
	         
	         session.delete(section);*/
	         tx.commit();
	         flag = true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return flag;
	   }
	   
	   public int getSectionIdValue()
	   {
		   	Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        int value=0;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            SQLQuery query = session.createSQLQuery("select MAX(section_id) from tbl_section");
	           
	            if(query.uniqueResult()!=null)
	            {
	            	String section_id=(String) query.uniqueResult();
	            	String section_counter=section_id.substring(7);
	            	value = Integer.parseInt(section_counter)+1;
	            }
	            else
	            	value=1;
	            
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
		   
		   return value;
	   }
	   
	   public boolean ifAlreadyExists(String sectionEmailId) {
			 boolean flag = getUserByUserId(sectionEmailId);
			 
			 return flag;
			 /*if(stud!=null && stud.getName().equals(studName) ){
				 return false;
			 }else{
				 return true;
			 }*/
		}
	   
	   public boolean ifAlreadyExists(Section newSection) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List sections = null;
		      try{
		         tx = session.beginTransaction();
		         sections = session.createQuery("FROM Section").list(); 
		         for (Iterator iterator = sections.iterator(); iterator.hasNext();){
		        	 Section section = (Section) iterator.next(); 
		            if(section.equals(newSection)) {
		            	System.out.println("Section already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
			 /*if(stud!=null && stud.getName().equals(studName) ){
				 return false;
			 }else{
				 return true;
			 }*/
		}
	   
	   
		public boolean getUserByUserId(String sectionEmailId) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Section section = null;
			 Query query=null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from Section where email_id='"+sectionEmailId+"'");
				 List list = query.list();
				 			 
				 if (list.isEmpty()) {
					 flag = false;
				 }
				 else {
					 flag = true;
				 }
				 if (!tx.wasCommitted()) {
					 tx.commit();
				 }
					 
			 } catch (Exception e) {
				 if (tx != null) {
					 tx.rollback();
				 }
				 e.printStackTrace();
			 } finally {
				 session.close();
			 }
			return flag;
		}
		
	    public Section getSectionBySectionEmail(String sectionEmail) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Section user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Section where email_id='"+sectionEmail+"'");
	            user = (Section)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user;
	    }
	    
	    public Section getSectionBySectionId(String sectionId) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Section user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Section where section_id='"+sectionId+"'");
	            user = (Section)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user;
	    }
	   
		/* Method to  READ all the section values */
		   public List listSections( ) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List sections = null;
		      try{
		         tx = session.beginTransaction();
		         sections = session.createQuery("FROM Section").list(); 
		         for (Iterator iterator =sections.iterator(); iterator.hasNext();){
		        	Section section = (Section) iterator.next(); 
		            System.out.print("Section Name: " + section.getSection_name()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return sections;
		   }
		   
		   public void SendMail(String sectionEmailId)
		   {
			   final String username = "merin1590@gmail.com";
				final String password = "jesuschrist123";
		 
				Properties props = new Properties();
				props.put("mail.smtp.auth", "true");
				props.put("mail.smtp.starttls.enable", "true");
				props.put("mail.smtp.host", "smtp.gmail.com");
				props.put("mail.smtp.port", "587");
		 
				javax.mail.Session session = javax.mail.Session.getInstance(props,
				  new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				  });
		 
				try {
		 
					Message message = new MimeMessage(session);
				
					message.setFrom(new InternetAddress("merin1590@gmail.com"));
					message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("merin1590@gmail.com")); // sectionEmailId should be passed here afterwards
					/* message.setRecipients(Message.RecipientType.TO,
						InternetAddress.parse(teacherEmailId)); */
					message.setSubject("Request for account Activation");
					
					
					Section section=getSectionBySectionEmail(sectionEmailId);
					//String teacher_name=teacher.getTeacher_name()+" "+teacher.getTeacher_lname();
					LoginService loginservice=new LoginService();
					User user=(User) loginservice.getUserByUserId(sectionEmailId,"User");
					String token=user.getSecret_key();
					
					String msg_text="Hi, "
							+ "\n\n Please click the below link to activate your account on Easy Attendance"
							+ "\n\n http://localhost:8080/Attendance/views/activationSuccess.jsp?token="+token;
					
							// Create the message part 
							MimeBodyPart messageBodyPart = new MimeBodyPart();

							// Fill the message
							messageBodyPart.setContent(msg_text,"text/html");

							MimeMultipart multipart = new MimeMultipart();
							multipart.addBodyPart(messageBodyPart);

							// Put parts in message
							message.setContent(multipart);
							message.setText(msg_text);
						Transport.send(message);
		 
					System.out.println("Mail sent!!");
		 
				} catch (MessagingException e) {
					throw new RuntimeException(e);
				} 

		   }
		   /* Method to UPDATE password of Admin */
/*		    public void updatePassword(String deptName, String newPassword){
		    	Session session = HibernateUtil.openSession();
		       Transaction tx = null;
		       try{
		          tx = session.beginTransaction();
		          Department user = getDepartmentByDeptName(deptName);
		          user.setPassword(newPassword);
		 		  session.update(user); 
		          tx.commit();
		       }catch (HibernateException e) {
		          if (tx!=null) tx.rollback();
		          e.printStackTrace(); 
		       }finally {
		          session.close(); 
		       }
		    }*/
}
